<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食堂名称" prop="canteenName">
        <el-input
          v-model="queryParams.canteenName"
          placeholder="请输入食堂名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fb:canteen:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fb:canteen:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fb:canteen:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fb:canteen:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-setting"
          size="mini"
          @click="handleDept"
          v-hasPermi="['fb:canteen:add']"
        >配置部门</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="canteenList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="食堂编号" align="center" prop="id" />
      <el-table-column label="食堂名称" align="center" prop="canteenName" />
      <el-table-column label="食堂电话" align="center" prop="canteenTel" />
      <el-table-column label="食堂地址" align="center" prop="canteenAddr" />
      <el-table-column label="负责人" align="center" prop="canteenPrincipal" />
      <el-table-column label="经度" width="50" align="center" prop="canteenLongitude" />
      <el-table-column label="纬度" width="50" align="center" prop="canteenLatitude" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="显示顺序" align="center" prop="canteenSort" />
      <el-table-column prop="canteenStatus" label="状态" :formatter="canteenStatusFormat" width="80"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-time"
            @click="handleSetTime(scope.row)"
            v-hasPermi="['fb:canteen:setMenu']"
          >营业时间</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleSetMenu(scope.row)"
            v-hasPermi="['fb:canteen:setMenu']"
          >设置菜单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fb:canteen:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fb:canteen:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食堂对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食堂名称" prop="canteenName">
          <el-input v-model="form.canteenName" placeholder="请输入食堂名称" />
        </el-form-item>
        <el-form-item label="食堂电话" prop="canteenTel">
          <el-input v-model="form.canteenTel" placeholder="请输入食堂电话" />
        </el-form-item>
        <el-form-item label="食堂地址" prop="canteenAddr">
          <el-input v-model="form.canteenAddr" placeholder="请输入食堂地址" />
        </el-form-item>
        <el-form-item label="负责人" prop="canteenPrincipal">
          <el-input v-model="form.canteenPrincipal" placeholder="请输入食堂负责人" />
        </el-form-item>
        <el-form-item label="食堂经度" prop="canteenLongitude">
          <el-input v-model="form.canteenLongitude" placeholder="请输入食堂经度" />
        </el-form-item>
        <el-form-item label="食堂纬度" prop="canteenLatitude">
          <el-input v-model="form.canteenLatitude" placeholder="请输入食堂纬度" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="canteenSort">
          <el-input-number v-model="form.canteenSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.canteenStatus">
            <el-radio
              v-for="dict in canteenStatus"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="店铺图片">
          <uploadImage v-model="form.logo"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--配置食堂下菜单的内容-->
    <el-dialog :title="title" :visible.sync="openMenu">
        <el-calendar>
          <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
          <template slot="dateCell" slot-scope="{date, data}">
            <p> <!--这里原本有动态绑定的class，去掉-->
              {{ data.day.split('-').split('-')}}
            </p>
          </template>
        </el-calendar>
    </el-dialog>

    <el-dialog title="设置食堂营业时间" :visible.sync="openSetTime">
      <el-table style="width: 100%" :data="canteenTimeList">
        <el-table-column label="类型" prop="mealType" width="180"> 
          <template slot-scope="scope">
            {{mealTypeFormat(scope.row.mealType)}}
          </template>
        </el-table-column>
        <el-table-column label="营业时间">
          <template slot-scope="scope">
            <el-time-select
              placeholder="起始时间"
              v-model="scope.row.startTime"
              :picker-options="{
                start: '06:00',
                step: '00:15',
                end: '24:00'
              }">
            </el-time-select>
            至
            <el-time-select
              placeholder="结束时间"
              v-model="scope.row.stopTime"
              :picker-options="{
                start: '06:00',
                step: '00:15',
                end: '24:00',
                minTime: scope.row.startTime
              }">
            </el-time-select>
          </template>
        </el-table-column>
        
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handSaveCanteenTime">保 存</el-button>
      </div>
    </el-dialog> 

    <el-dialog title="部门配置"  :visible.sync="openDeptAndCanteen" width="500px">
      <div class="">
        <el-row :gutter="20">
          <!--部门数据-->
          <el-col :span="4" :sm="12">
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                size="small"
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                style="background:#f5f7fa"
                highlight-current
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>
          <!--食堂数据-->
          <el-col :span="20" :sm="12">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>选择食堂</span>
                <el-button type="success" icon="el-icon-check" @click="handSaveCanteenDept" style="float: right;padding: 2px 2px;" size="mini" circle></el-button>
              </div>
              <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 10px 0;"></div>
              <el-checkbox-group v-model="checkedCanteens" @change="handleCheckedCanteensChange">
                <el-checkbox v-for="cc in canteenListAll" :label="cc" :key="cc.id">{{cc.canteenName}}</el-checkbox>
              </el-checkbox-group>
            </el-card>
          </el-col>
        </el-row>
      </div>      
    </el-dialog> 

  </div>
</template>

<script>
import { listCanteen, getCanteen, delCanteen, addCanteen, updateCanteen, exportCanteen,setCanteenTime,saveCanteenTime,listCanteenAll,selectCanteenDept,saveCanteenDept } from "@/api/fb/canteen";
import UploadImage from '@/components/UploadImage';
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Canteen",
  components: {
     UploadImage,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食堂表格数据
      canteenList: [],
      // 弹出层标题
      title: "",
      //状态
      canteenStatus: [],
      // 是否显示弹出层
      open: false,
      //菜单配置显示弹出层
      openMenu: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        canteenName: null,
        canteenTel: null,
        canteenAddr: null,
        canteenPrincipal: null,
        canteenLongitude: null,
        canteenLatitude: null,
        canteenSort: null,
        dataScope: null,
        canteenStatus: null,
      },
      //营业时间显示弹出层
      openSetTime: false,
      canteenTimeList: [],
      //餐类型
      mealTypeOptions: [],
      //部门与食堂显示弹出层
      openDeptAndCanteen: false,
      // 部门树选项
      deptOptions: undefined,
      //选中的部门ID
      checkDeptId: "",
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      //全部食堂数据
      canteenListAll: [],
      checkAll: false,
      isIndeterminate: undefined,
      //已选值
      checkedCanteens: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        canteenSort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
        canteenStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.canteenStatus = response.data;
    });
    //查询餐类
    this.getDicts("fb_meal_type").then(response => {
        this.mealTypeOptions = response.data;
    });
  },
  methods: {
    dealMyDate(v) {
        console.log(v)
        let len = this.resDate.length
        let res = ""

        return res
    },
    /** 查询食堂列表 */
    getList() {
      this.loading = true;
      listCanteen(this.queryParams).then(response => {
        this.canteenList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 菜单状态字典翻译
    canteenStatusFormat(row, column) {
      return this.selectDictLabel(this.canteenStatus, row.canteenStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        canteenName: null,
        canteenTel: null,
        canteenAddr: null,
        canteenPrincipal: null,
        canteenLongitude: null,
        canteenLatitude: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        canteenSort: null,
        dataScope: null,
        canteenStatus: "0",
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加食堂";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCanteen(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改食堂";
      });
    },
    /**配置功能 */
    handleSetMenu(row){
      this.reset();
      const id = row.id || this.ids
      this.$router.push({
          name:'CanteenDate',
          params:{
            canteenId:id
          }
        })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCanteen(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCanteen(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除食堂编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCanteen(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有食堂数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCanteen(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 设置营业时间*/
    handleSetTime(row){
      this.reset();
      const id = row.id || this.ids;
      setCanteenTime(id).then(response => {
        this.canteenTimeList=response.data;
        this.openSetTime = true;
      });
    },
    /** 保存营业时间*/
    handSaveCanteenTime(){
      console.log("canteenTimeList",this.canteenTimeList)
      saveCanteenTime(this.canteenTimeList).then(response =>{
        this.msgSuccess(response.msg);
        this.canteenTimeList=[];
        this.openSetTime = false;
      });
    },
    //餐类型字段翻译
    mealTypeFormat(mealType) {
      return this.selectDictLabel(this.mealTypeOptions,mealType);
    },
    //弹出部分与食堂配置窗
    handleDept(){
      //加载部门树结构
      this.checkedCanteens = [];
      this.isIndeterminate = false;
      this.getTreeselect();
      this.getListCanteenAll();
      this.openDeptAndCanteen = true;
    },
    //查询全部食堂
    getListCanteenAll(){
      listCanteenAll().then(response =>{
        this.canteenListAll = response.data
        console.log('listCanteenAll',this.canteenListAll);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.checkDeptId = data.id;
      this.checkedCanteens = [];
      //调用查询方法，查询该部门下已有的食堂信息
      selectCanteenDept(this.checkDeptId).then(response => {
        let arr = [];
        response.data.forEach(item => {
          this.canteenListAll.forEach(obj => {
            if(obj.id === item.id)arr.push(obj)
          })
        })
        if(response.data.length>0){this.isIndeterminate = true}else{this.isIndeterminate = false};
        this.checkedCanteens = arr;
        console.log('response',response.data);
      });
    },
    handleCheckAllChange(val) {
      this.checkedCanteens = val ? this.canteenListAll : [];
      this.isIndeterminate = false;
    },
    handleCheckedCanteensChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.canteenListAll.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.canteenListAll.length;
    },
    /**保存部门与食堂 */
    handSaveCanteenDept() {
      console.log("handSaveCanteenDept",this.checkedCanteens);
      let arr = [];
      this.checkedCanteens.forEach(obj => {
        arr.push(obj.id+"");
      })
      saveCanteenDept({deptId:this.checkDeptId,canteens:arr}).then(response => {
        this.msgSuccess(response.msg);
      })
    }
  },
  watch:{
    checkedCanteens(val){
      console.log('val',val);
    },
    isIndeterminate(val){
      console.log('isIndeterminate',val);
    }
  }
};
</script>
